/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package be.vdab.servlets;

import be.vdab.dao.VoorstellingDAO;
import be.vdab.entiteit.Klant;
import be.vdab.entiteit.Reservatie;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author tom.vanpoucke
 */
@WebServlet("/voorstellingen/bevestigen.htm")
public class BevestigingServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static final VoorstellingDAO voorstellingDAO = new VoorstellingDAO();
    private static final String VIEW = "/WEB-INF/JSP/bevestigen.jsp";
    private static final String SUCCES = "/voorstellingen/bevestigen.htm";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        if(session != null){
            List<Reservatie> gelukt = (List<Reservatie>) session.getAttribute("gelukt");
            List<Reservatie> mislukt = (List<Reservatie>) session.getAttribute("mislukt");
            session.removeAttribute("klant");
            request.setAttribute("gelukt", gelukt);
            request.setAttribute("mislukt", mislukt);
            RequestDispatcher dispatcher = request.getRequestDispatcher(VIEW);
            dispatcher.forward(request, response);   
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if(session != null){
            Set<Reservatie> mandje = (Set<Reservatie>) session.getAttribute("mandje");
            Klant klant = (Klant) session.getAttribute("klant");
            List<Reservatie> gelukt = new ArrayList<Reservatie>();
            List<Reservatie> mislukt = new ArrayList<Reservatie>();
            for(Reservatie reservatie : mandje){
                try {
                    voorstellingDAO.reserveren(reservatie, klant);
                    gelukt.add(reservatie);
                }catch(SQLException ex){
                    mislukt.add(reservatie);
                }

            }
            session.removeAttribute("mandje");
            session.setAttribute("gelukt", gelukt);
            session.setAttribute("mislukt", mislukt);
            response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + SUCCES));
        }
    }
}
